<?php
namespace app\controllers;

use app\models\order\Order;
use app\models\Queue;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class MonthController extends Controller
{
    // 每月1号5点执行
    // 0 5 1 * * /usr/bin/curl http://http://j2-api.97app.cn/month
    public function actionIndex()
    {
        $month = date('Ym');
        $month = intval($month);

        // 检查是否已返
        $is = Queue::find()
            ->where(['month' => $month])
            ->andWhere(['status' => 1])
            ->one();
        if ($is) {
            return '已返';
        }

        // 处理佣金
        $list = $this->go();
        // var_dump($list);exit;

        foreach ($list as $item) {
            $commission = $this->commissionCalc($list, $item);
            // echo $commission, "<br>";

            // 可能出现负
            if ($commission <= 0) {
                $commission = 0;
            }

            $this->saveCommission($item['id'], $commission, '99', '分红奖');
        }

        // 保存已返状态
        $queue = Queue::findOne(['month' => $month]);
        if (!$queue) {
            $queue = new Queue();
            $queue->month = $month;
        }
        $queue->status = 1;
        $queue->save();

        echo $month;
    }

    protected function saveCommission($user_id, $balance, $type, $name)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = 0;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $balance;
                $account->save();
            }
        }
    }

    public function go($referrer_id = 0, $list = [])
    {
        $query = User::find();
        if ($referrer_id > 0) {
            $query->where(['id' => $referrer_id]);
        } else {
            // $query->where(['referrer_id' => $referrer_id]);
            // 第1批
            $query->andWhere(['level' => [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]]);
        }

        $users = $query->andWhere(['level' => [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]])
            ->orderBy(['id' => SORT_ASC])
            ->select(['id'])
            ->asArray()
            ->all();

        // 第1批, 筛选(不能是别人的管理)
        if ($referrer_id == 0) {
            $tmp = [];
            foreach ($users as $u) {
                $chain = Chain::getReferrerChain($u['id'], [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]);
                if ($chain) {
                    continue;
                }
                array_push($tmp, $u);
            }
            $users = $tmp;
        }

        $users = ArrayHelper::getColumn($users, 'id');

        // 2) 团队
        $team = [];
        foreach ($users as $user) {

            // 全部
            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['svip1'],
                UserLevel::$keys['svip2'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            // 管理
            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['svip2'],
                UserLevel::$keys['svip1'],
            ], ['id']);

            $manager = ArrayHelper::getColumn($manager, 'id');

            $team[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager
            ];
        }

        $users = $team;

        // 3) 业绩
        foreach ($users as $user) {
            $orders = Order::find()
                ->where(['user_id' => array_merge([$user['id']], $user['children'])])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                // 上个月的 (下个月1号返)
                // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                // todo 这里是累计的, 每个月返1次就行了
                ->all();

            $sum = 0;
            foreach ($orders as $order) {
                $sum += $order->total_pay;
            }

            $user['sum'] = $sum;
            $user['amount'] = $this->getAmount($sum);

            if (!key_exists($user['id'], $list)) {
                $list[$user['id']] = $user;
            }

            // // 子团队业务
            foreach ($user['manager'] as $item) {
                $list = $this->go($item, $list);
            }

        }

        return $list;
    }

    protected function getAmount($sum)
    {
        if ($sum == 0) {
            return 0;
        }

        $model = ZSetting::find()
            ->where(['<=', 'start', $sum])
            ->andWhere(['>=', 'end', $sum])
            ->one();

        // echo $model->createCommand()->getRawSql();exit;

        if ($model) {
            return $model->amount;
        }

        // 最大
        $last = ZSetting::find()
            ->orderBy(['amount' => SORT_DESC])
            ->one();
        if ($sum >= $last->end) {
            return $last->amount;
        }

        return 0;
    }

    public function commissionCalc($list, $item)
    {
        // 找出需要减掉的(可能有多个)
        $data = [];
        foreach ($item['manager'] as $v) {
            $chain = Chain::getReferrerChain($v, [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]);
            if ($chain) {

                if ($chain[0]['id'] == $item['id']) {
                    array_push($data, $v);
                }
            }
        }

        // var_dump($data);exit;

        $sub = 0;
        foreach ($list as $v) {
            if (in_array($v['id'], $data)) {
                $sub += $v['amount'];
            }
        }

        return $item['amount'] - $sub;
    }
}